#!/usr/bin/python
"""
Takes all the alt*.txt files
runs mapcalc and creates the *_final raster
Run from the ca_c location in arc zone 2, final_matt mapset
"""
import os
import sys

IMPACTS = [x.strip() for x in open('impact_layers.txt').readlines()]
POSTFIX = "_model_avg"

def do_mapcalc(mod_file=None):
    mods = {}
    if mod_file:
        mod_lines = open(mod_file + ".txt").readlines()
        for m in mod_lines:
            x = m.split()
            imp = x[0].strip()
            factor = float(x[1].strip())
            if imp in IMPACTS:
                mods[imp] = factor

    mod_impacts = []
    for impact in IMPACTS:
        if impact in mods.keys():
            # TODO scale that impact according to mod file
            mod_impacts.append("(%s%s * %s)" % (impact, POSTFIX, mods[impact]))
        else:
            mod_impacts.append(impact + POSTFIX)

    os.popen('g.remove rast=%s_final' % mod_file)
    cmd = "r.mapcalc %s_final = '%s'" % (mod_file, ' + '.join(mod_impacts))
    os.popen(cmd).readlines()
    return cmd
    
import glob
mods = [x.replace('.txt','') for x in glob.glob('alt_*.txt')] 
for mod in mods:
    print 'Calculating',mod
    do_mapcalc(mod)
    print
